package com.examlpe.lotterysystem.service.activitystatus.operater;

import com.examlpe.lotterysystem.dao.dataobject.ActivityDO;
import com.examlpe.lotterysystem.dao.mapper.ActivityMapper;
import com.examlpe.lotterysystem.dao.mapper.ActivityPrizeMapper;
import com.examlpe.lotterysystem.service.dto.ConvertActivityStatusDTO;
import com.examlpe.lotterysystem.service.enums.ActivityPrizeStatusEnum;
import com.examlpe.lotterysystem.service.enums.ActivityStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ActivityOperater extends AbstractActivityOperater{

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;

    @Override
    public Integer sequence() {
        return 2;
    }

    @Override
    public Boolean needConvert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        Long activityId = convertActivityStatusDTO.getActivityId();
        ActivityStatusEnum targetActivityStatus = convertActivityStatusDTO.getTargetActivityStatus();
        if(null == activityId
           || null == targetActivityStatus) {
            return false;
        }
        //查询活动是否存在
        ActivityDO activityDO = activityMapper.selectActivityById(activityId);
        if(null == activityDO) {
            return false;
        }
        //活动状态与传入状态一致,不进行转换
        if(targetActivityStatus.name().equalsIgnoreCase(activityDO.getStatus())) {
            return false;
        }
        //奖品没有抽完，不进行活动状态扭转
        int num = activityPrizeMapper.countPrize(activityId, ActivityPrizeStatusEnum.INIT.name());
        if(num > 0) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean convert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        try{
            activityMapper.updateStatus(convertActivityStatusDTO.getActivityId(),
                    convertActivityStatusDTO.getTargetActivityStatus().name());
            return true;
        }catch (Exception e) {
            return false;
        }
    }
}
